package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.IotDevice;
import com.ruoyi.system.mapper.IotDeviceMapper;
import com.ruoyi.system.service.SendInstructsService;
import com.ruoyi.system.netty.BootNettyChannelInboundHandlerAdapter;
import com.ruoyi.system.utils.ElectricityMeterUtil;
import com.ruoyi.system.utils.InstructConstant;
import com.ruoyi.system.utils.InstructTypeConstant;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;

@Service("sendInstructsService")
public class SendInstructsServiceImpl implements SendInstructsService {

    @Resource
    private RedisCache redisCache;
    @Resource
    IotDeviceMapper deviceMapper;

    @Override
    public Object[] sendInstructs(String context, String ip, HttpServletRequest request, String deviceCode, String operationType) {
        try {
            Long countTimeLong = 0L;
            a:
            while (true) {
                //防止一台设备同时下发多条指令，如果缓存中有记录则表示上次的操作还未完成
                String type = redisCache.getCacheObject(InstructConstant.handleInstructs + deviceCode);
                if (countTimeLong > 20000) {
                    //超过20秒没有接到指令的返回，则自动撤销上次的操作
                    redisCache.deleteObject(InstructConstant.handleInstructs + deviceCode);
                    break;
                }
                Thread.sleep(500);
                countTimeLong = countTimeLong + 500;
                if (StringUtils.isEmpty(type)) {
                    //20秒
                    redisCache.setCacheObject(InstructConstant.handleInstructs + deviceCode, operationType, 200, TimeUnit.MILLISECONDS);
                    byte[] b = ElectricityMeterUtil.fromHexString(context);
                    ChannelGroup channelGroup = BootNettyChannelInboundHandlerAdapter.getChannels();
                    Iterator<Channel> channelIterator = channelGroup.iterator();
                    b:while (channelIterator.hasNext()) {
                        Channel channel = channelIterator.next();
                        InetSocketAddress insocket = (InetSocketAddress) channel.remoteAddress();
                        //给指定客户端ip(水电网关)发送消息
                        if (ip.equals(insocket.toString())) {
                            channel.writeAndFlush(Unpooled.copiedBuffer(b));
                            channel.flush();
                            break a;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Object[]{context, ip, request, deviceCode, operationType};
    }

    @Override
    public void callbackInstructResultMsg(String ip, String returnStr) {
        String notFEStr = returnStr.substring(returnStr.indexOf("68") + 2);
//        String addressNo = notFEStr.substring(0, notFEStr.indexOf("68"));
        String deviceNo = ElectricityMeterUtil.addressConvertNo(notFEStr, true);
        String operationType = redisCache.getCacheObject(InstructConstant.handleInstructs + deviceNo);
        redisCache.deleteObject(InstructConstant.handleInstructs + deviceNo);
        handleOperation(deviceNo, operationType, notFEStr);
    }

    private void handleOperation(String deviceNo, String operationType, String notFEstr) {
        LambdaQueryWrapper<IotDevice> wraper = new LambdaQueryWrapper<>();
        wraper.eq(IotDevice::getDeviceCode,deviceNo);
        IotDevice vo = new IotDevice();
        //合总电闸，拉闸或合闸后修改设备表状态
        if (InstructTypeConstant.E_MAIN_GATE_NO.getKey().equals(operationType)){
            vo.setElectricityStatus("1");
            deviceMapper.updateIotDevice(vo);
        }
        //拉总电闸
        if (InstructTypeConstant.E_MAIN_GATE_OFF.getKey().equals(operationType)){
            vo.setElectricityStatus("0");
            deviceMapper.updateIotDevice(vo);
        }
    }

//    @Override
//    public void handleGateWayStatus(String clientIp, Object o, boolean b) {
//
//    }
}
